<template>
  <section>
    <search-box>
      <div class="flex-row justify-between">
        <div class="search-box">
          <el-select
            class="w-180 m-r-10"
            v-model="searchData.region_id"
            placeholder="请选择可用区" @change="fnRegionChange">
            <el-option v-for="(item, index) in regionList" :key="index" :label="item.region_name" :value="item.region_id"></el-option>
          </el-select>
          <el-select
            class="w-180 m-r-10"
            v-model="searchData.cluster"
            placeholder="请选择边缘集群">
            <el-option v-for="(item, index) in clusterList" :key="index" :label="item.cluster_name" :value="item.cluster_id"></el-option>
          </el-select>
          <el-input
            class="search-input m-r-10"
            v-model="searchData.key"
            clearable
            placeholder="请输入主机名称">
          </el-input>
          <el-button type="primary" @click="fnGetEdgeNode">查询</el-button>
        </div>
        <div>
          <el-button type="primary" @click="FnAddEdgeNode" :disabled="FnBtnDisabled('eks_2_edge_add_node')">添加节点</el-button>
        </div>
      </div>
    </search-box>
    <el-table :data="goodslist" border stripe>
      <el-table-column prop="node_id" min-width="110" label="ID"></el-table-column>
      <el-table-column prop="node_name" min-width="110" label="主机名称"></el-table-column>
      <el-table-column label="可用区">
        <template #default="scope">
          {{scope.row.available_zone_name ? scope.row.available_zone_name : '-'}}
        </template>
      </el-table-column>
      <el-table-column prop="goods_id" min-width="250" label="配置">
        <template #default="{row}">
          <div class="display-flex">
            <div class="w-150">
              CPU: {{ row.cpu_size >= 0 ? `${row.cpu_size}核` : '-' }} | 内存: {{ row.ram_size >= 0 ? `${row.ram_size}G` : '-' }}
              <br>
              GPU数量: {{ row.gpu_sum >= 0 ? `${row.gpu_sum}` : '-' }}
            </div>
            <div class="flex-item">
              <el-button type="text" @click="fnCheckConfigDetail(row)">配置详情</el-button>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态" min-width="110">
        <template #default="scope">
          <span v-if="scope.row.node_status === 'unknown'">-</span>
          <span v-else :class="statusObj[scope.row.node_status]">{{scope.row.status_str}}</span>
        </template>
      </el-table-column>
      <el-table-column label="网络" min-width="110">
        <template #default="{row}">
          <div>{{row.private_ip}}</div>
          <div>{{row.subnet_name}}</div>
        </template>
      </el-table-column>
      <el-table-column label="K8S状态" min-width="110">
        <template #default="{row}">
          <span v-if="row.k8s_status === 'Ready'" class="running">{{ row.k8s_status }}</span>
          <span v-else-if="row.k8s_status === 'NotReady'" class="error">{{ row.k8s_status }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="调度" min-width="110">
        <template #default="{row}">
          <div v-if="row.node_type === 'master' || row.source_type ==='other'">-</div>
          <div v-else>{{row.schedulable && row.schedulable == 1 ? "可调度" : "不可调度" }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="node_type" label="节点类型" min-width="110"></el-table-column>
      <el-table-column prop="source" label="节点来源" min-width="110"></el-table-column>
      <el-table-column label="添加时间" min-width="160">
        <template #default="scope">
          {{scope.row.create_time ? scope.row.create_time : '-'}}
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="160">
        <template #default="{row}">
          <template v-if="row.node_type === 'worker' && row.source_type !== 'ecs' && row.source_type !== 'bms'">
            <el-button 
              type="text" 
              @click="fnSetSchedulable(row)"
              :disabled="FnBtnDisabled('eks_2_edge_schedule') || row.node_status !== 'running'">
              {{ row.schedulable === 1 ? '设置为不可调度' : '设置为可调度' }}
            </el-button>
          </template>
          <el-button 
            type="text" 
            @click="fnRemoveNode(row)"
            v-if="row.source_type !== 'ecs' && row.source_type !== 'bms'"
            :disabled="FnBtnDisabled('eks_2_edge_remove') || (row.source_type === 'bms' && row.bill_method === '1') || (row.node_status !== 'running' && row.node_status !== 'unknown' && row.node_status !== 'error')">
            移除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="page-box">
      <el-pagination
              @current-change="handleCurrentChange"
              :current-page="page.index"
              :page-size="page.size"
              layout="total, prev, pager, next"
              :total="page.total">
      </el-pagination>
    </div>
    <el-dialog
      title="配置详情"
      v-model="dialogVisible"
      width="500px">
      <el-form label-width="auto">
        <el-form-item label="CPU:">
          {{ config.cpu_desc ?? '-' }}
        </el-form-item>
        <el-form-item label="内存:">
          {{ config.mem_desc ?? '-' }}
        </el-form-item>
        <el-form-item label="存储:">
          {{ config.disk_desc ?? '-' }}
        </el-form-item>
        <el-form-item label="扩展配置:">
          {{ config.extend_card_desc ?? '-' }}
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false" type="primary">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </section>
</template>
<script setup>
import { nextTick, onMounted, reactive, ref, watch } from 'vue';
import searchBox from '@/components/search-box.vue'
import edgeService from '@/service/eks/edge'
import { statusObj } from '@/utils/console.js'
import { authBtnDisabled } from '@/utils/auth.js'
import { useRoute, useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()
const FnBtnDisabled = (key) => {
  return authBtnDisabled(key, route.meta.name)
}
const searchData = reactive({
  region_id: '',
  cluster: '',
  key: ''
})
const regionList = ref([])
const clusterList = ref([])

const getRegionList = async () => {
  await edgeService.getRegionList().then((res) => {
    if (res.code === 'Success') {
      regionList.value = res.data ? res.data : [];
      if(route.query?.region_id) {
        searchData.region_id = route.query?.region_id
      } else {
        searchData.region_id = regionList.value.length ? regionList.value[0].region_id : ''
      }
    }
  })
}
const getClusterList = async () => {
  await edgeService.getEdgeClusters({region_id: searchData.region_id}).then((res) => {
    if (res.code === 'Success') {
      clusterList.value = res.data ? res.data : [];
      if(route.query?.cluster_id && !isChange.value) {
        searchData.cluster = route.query?.cluster_id
      } else {
        nextTick(() => {
          searchData.cluster = clusterList.value.length ? clusterList.value[0].cluster_id : ''
        })
      }
    }
  })
}
const page = reactive({
  index: 1,
  size: 10,
  total: 0
})
const goodslist = ref([])
const fnGetEdgeNode = async () => {
  let params = {
    cluster_id: searchData.cluster,
    keyword: searchData.key,
    page_index: page.index,
    page_size: page.size
  }
  await edgeService.getEdgeNodes(params).then((res) => {
    if(res.code === 'Success') {
      page.total = res.page.total_count
      page.size = res.page.page_size
      goodslist.value = res.data ? res.data : []
    }
  })
}

getRegionList().then(() => {
  return getClusterList()
}).then(() => {
  return fnGetEdgeNode()
})
const isChange = ref(false)
const fnRegionChange = (val) => {
  searchData.cluster = ''
  clusterList.value = []
  page.total = 0
  page.size = 10
  goodslist.value = []
  if(val) {
    isChange.value = true
    getClusterList().then(() => {
      return fnGetEdgeNode()
    })
  }
}
// 移除节点
const fnRemoveNode = (row) => {
  ElMessageBox.confirm('确认移除该节点资源？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    let params = {
      cluster_id: row.cluster_id,
      node_id: row.node_id
    }
    edgeService.delEdgeNode(params).then((res) => {
      if(res.code === 'Success') {
        ElMessage.success('移除成功')
        fnGetEdgeNode()
      }
    })
  }).catch(() => {})
}

// 添加节点
const FnAddEdgeNode = () => {
  router.push("/eks/edgeCluster/node/add")
}
// 配置详情
const config = ref(null)
const dialogVisible = ref(false)
const fnCheckConfigDetail = (row) => {
  config.value = row.cfg_info
  dialogVisible.value = true
}
// 调度
const fnSetSchedulable = (row) => {
  ElMessageBox.confirm(`确定将该节点设置为${row.schedulable == 1 ? '不可调度' : '可调度'}？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    let params = {
      cluster_id: row.cluster_id,
      node_id: row.node_id,
      schedule: row.schedulable == 1 ? false : true
    } 
    edgeService.setSchedule(params).then(res => {
      if(res.code === 'Success') {
        ElMessage.success('设置成功')
        getEdgeNodes()
      }
    })
  }).catch(() => {})
}
</script>
<style scoped lang="scss">
.running {
  color: #09AE40;
}
.error {
  color: #EB2A2A;
}
.deleting {
  color: #F5AB18;
}
.stop {
  color: #9D9DAD;
}
</style>